package ysq.xyg.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.recovery.model.po.RecoveryRecord;
import ysq.xyg.recovery.service.PowerMemberService;
import ysq.xyg.recovery.service.RecoveryRecordService;
import ysq.xyg.shop.dao.ShopOrderDao;
import ysq.xyg.shop.model.po.ShopItem;
import ysq.xyg.shop.model.po.ShopOrder;
import ysq.xyg.shop.model.vo.ShopOrderVo;
import ysq.xyg.shop.service.ShopItemService;
import ysq.xyg.shop.service.ShopOrderService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.wxapi.api.WxApiClient;
import ysq.xyg.wxapi.model.base.TemplateMessage;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城模块-商品订单管理service实现
 *
 * @author congcong tao
 * @date 2019-8-17 8:12:11
 */
@Service("shopOrderService")
public class ShopOrderServiceImpl extends BaseServiceImpl<ShopOrder> implements ShopOrderService {

    @Resource
    private PowerMemberService powerMemberService;
    @Resource
    private RecoveryRecordService recoveryRecordService;
    @Resource
    private ShopItemService shopItemService;
    @Resource
    private WebMemberService webMemberService;
    @Resource
    private ShopOrderDao shopOrderDao;

    private ShopOrder shopOrder;

    @Autowired
    public void setBaseDao(ShopOrderDao shopOrderDao) {
        this.baseDao = shopOrderDao;
    }

    /**
     * 分页查询
     *
     * @param shopOrderVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-17 8:12:11
     */
    @Override
    public ReturnEntity page(ShopOrderVo shopOrderVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<ShopOrder> list = acceptList(shopOrderVo);
        PageInfo<ShopOrder> page=new PageInfo<ShopOrder>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(ShopOrderVo shopOrderVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<ShopOrder> list = shopOrderDao.selectEntityList(shopOrderVo);
        PageInfo<ShopOrder> page=new PageInfo<ShopOrder>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param shopOrderVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-17 8:12:11
     */
    @Override
    public ReturnEntity addOrUpdate(ShopOrderVo shopOrderVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(shopOrderVo.getId())){
            shopOrder=new ShopOrder(currentUser);
            isUpate=false;
        }else{
            shopOrder=selectByPrimaryKey(shopOrderVo.getId());
            if(ObjectUtil.isNull(shopOrder)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            shopOrder.setUpdateTime(new Date());
            shopOrder.setUpdateUser(currentUser.getId());
        }
        shopOrder.setMemberId(shopOrderVo.getMemberId());
        shopOrder.setItemId(shopOrderVo.getItemId());
        shopOrder.setItemName(shopOrderVo.getItemName());
        shopOrder.setImage(shopOrderVo.getImage());
        shopOrder.setIntegral(shopOrderVo.getIntegral());
        shopOrder.setStatus(shopOrderVo.getStatus());
        shopOrder.setMemberAddress(shopOrderVo.getMemberAddress());
        shopOrder.setMemberPhone(shopOrderVo.getMemberPhone());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(shopOrder);
        }else{
            num=insert(shopOrder);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-8-17 8:12:11
     */
    @Override
    public ReturnEntity delete(String id, SysUser currentUser) {
        ShopOrder shopOrder=selectByPrimaryKey(id);
        if(shopOrder!=null){
            shopOrder.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            shopOrder.setUpdateTime(new Date());
            shopOrder.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(shopOrder);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param shopOrderVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-8-17 8:12:11
     */
    @Override
    public List<ShopOrder> acceptList(ShopOrderVo shopOrderVo){
        Example example = new Example(ShopOrder.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(shopOrderVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",shopOrderVo.getRemoveTag());
        }
        if(StringUtil.isNotEmpty(shopOrderVo.getMemberId())){
            criteria.andEqualTo("memberId",shopOrderVo.getMemberId());
        }
        if(StringUtil.isNotEmpty(shopOrderVo.getMemberName())){
            criteria.andLike("memberName", "%" + shopOrderVo.getMemberName() + "%");
        }
        if(StringUtil.isNotEmpty(shopOrderVo.getItemName())){
            criteria.andLike("itemName", "%" + shopOrderVo.getItemName() + "%");
        }
        if(StringUtil.isNotEmpty(shopOrderVo.getMemberPhone())){
            criteria.andLike("memberPhone", "%" + shopOrderVo.getMemberPhone() + "%");
        }
        example.setOrderByClause(" update_time desc");
        return shopOrderDao.selectByExample(example);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity shopOrderSave(String itemId, String memberId, String memberName, String memberPhone, String memberAddress) {
        // 需要人员信息
        WebMember webMember = webMemberService.selectByPrimaryKey(memberId);
        ShopItem shopItem = shopItemService.selectByPrimaryKey(itemId);
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setId(BaseUtil.uId());
        shopOrder.setMemberId(memberId);
        shopOrder.setMemberName(memberName);
        shopOrder.setMemberPhone(memberPhone);
        shopOrder.setMemberAddress(memberAddress);
        shopOrder.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        shopOrder.setCreateTime(DateUtil.date());
        shopOrder.setUpdateTime(DateUtil.date());
        shopOrder.setItemId(itemId);
        shopOrder.setItemName(shopItem.getTitle());
        shopOrder.setImage(shopItem.getImage());
        shopOrder.setIntegral(shopItem.getIntegral());
        shopOrder.setStatus(BaseConstant.INTEGRAL_ORDER_STATUS_ONE);
        int num = this.insert(shopOrder);
        if (num > 0) {
            RecoveryRecord recoveryRecord = new RecoveryRecord();
            recoveryRecord.setId(BaseUtil.uId());
            recoveryRecord.setMemberId(memberId);
            recoveryRecord.setMoney(shopItem.getIntegral());
            recoveryRecord.setDescription(String.format("兑换物品减去%s积分", shopItem.getIntegral()));
            recoveryRecord.setCreateTime(DateUtil.date());
            recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
            recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
            recoveryRecord.setType(BaseConstant.RECORD_STATUS_CUT_SCORE);
            recoveryRecordService.insert(recoveryRecord);
            // 积分减去
            webMember.setScore(webMember.getScore() - Integer.parseInt(shopItem.getIntegral()));
            webMemberService.updateByPrimaryKey(webMember);
         /*   String openId = powerMemberService.selectOpenIdByType(BaseConstant.POWER_MEMBER_ITEM);
            // 兑换提醒
            TemplateMessage templateMessage=new TemplateMessage();
            templateMessage.setUrl("");
            templateMessage.setOpenid(openId);
            templateMessage.setTemplateId("gZOTfW30xhYD21x5cfTlXEC6L9asujq3mjhzdGWllPo");
            Map<String,String> data=new HashMap<String, String>();
            data.put("first", "您有一个用户" + memberName + "，兑换的商品");
            data.put("keyword1", shopItem.getTitle());
            data.put("keyword2", shopItem.getIntegral() + "个积分");
            data.put("keyword3", DateUtil.formatDateTime(DateUtil.date()));
            data.put("keyword4", "无");
            data.put("remark", "备注：请尽快查处理");
            templateMessage.setDataMap(data);
            WxApiClient.sendTempletNotice(templateMessage);*/
            return new ReturnEntity();
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateStatus(String id, String status, String manageRemark) {
        if(StringUtil.isEmpty(id)){
            return new ReturnEntity(BaseConstant.FAIL, "ID为空");
        }
        ShopOrder shopOrder = this.selectByPrimaryKey(id);
        shopOrder.setManageRemark(manageRemark);
        shopOrder.setStatus(status);
        int info = this.updateByPrimaryKey(shopOrder);
        if (info <= 0) {
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        if (StringUtils.equals(status, BaseConstant.RECOVERY_WASTE_MEMBER_STATUS_THREE)) {
            // 如果是驳回，需要将积分还给用户
            if (StringUtils.isNotEmpty(shopOrder.getIntegral())) {
                WebMember webMember = webMemberService.selectByPrimaryKey(shopOrder.getMemberId());
                webMember.setScore(webMember.getScore() + Integer.parseInt(shopOrder.getIntegral()));
                int num = webMemberService.updateByPrimaryKey(webMember);

                RecoveryRecord recoveryRecord = new RecoveryRecord();
                recoveryRecord.setId(BaseUtil.uId());
                recoveryRecord.setMemberId(webMember.getId());
                recoveryRecord.setMoney(shopOrder.getIntegral());
                recoveryRecord.setDescription(String.format("兑换物品返回%s积分", shopOrder.getIntegral()));
                recoveryRecord.setCreateTime(DateUtil.date());
                recoveryRecord.setUpdateTime(recoveryRecord.getCreateTime());
                recoveryRecord.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
                recoveryRecord.setType(BaseConstant.RECORD_STATUS_ADD_SCORE);
                recoveryRecordService.insert(recoveryRecord);

                if (num <= 0) {
                    return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
                }
            }
        }
        return new ReturnEntity();
    }
}
